<?php

if (!function_exists('json_decode')) {
    throw new Exception('Openid needs the JSON PHP extension.');
}

require_once 'Api/Api.php';
require_once 'Api/Object.php';
require_once 'Constant.php';

class Payment extends Api {

    private $_user_id;

    public function call_api($name, $paras) {
        try {
            $result = $this->_api('service/payment/token', $this->get_api_key());
            $result = Controller_Helper_SimpleXML::xml_to_array($result);
        } catch (Exception $e) {
            $result = array('status' => 0, 'message' => 'Invalid API name or parameters!');
        }
        if ($result['status'] != PaymentConstant::RESPONSE_STATUS_OK) {
            return $result;
        }
        $token = $result['data']['token'];
        try {
            $result = $this->_api('service/payment/' . $name, $token, $paras);            
            $result = Controller_Helper_SimpleXML::xml_to_array($result);
        } catch (Exception $e) {
            $result = array('status' => 0, 'message' => 'Invalid API name or parameters!');
        }

        return $result;
    }

    public function api($path, $paras = null) {
        $paras['code'] = $this->get_api_code();
        $paras['time'] = time();
        $data = '';
        foreach ($paras as $para) {
            $data = $data . ' ' . $para;
        }
        $data = $data . ' ' . $this->get_api_key();
        try {
            $result = $this->_api($path, md5(sha1($data)), $paras);
            $result = Controller_Helper_SimpleXML::xml_to_array($result);
        } catch (Exception $e) {
            $result = array('status' => 0, 'message' => 'Invalid API name or parameters!');
        }
        return $result;
    }

    public function allow_payment_method($name) {
        $pay_method = $this->get_api_config('method');
        if (empty($pay_method)) {
            return true;
        }
        if (isset($pay_method[$name])) {
            return $pay_method[$name];
        }
        return true;
    }

    public static function load() {
        //do not delete this method;
    }

    private static $_instance;

    /**
     * @return Library_Payment_Client
     */
    public static function instance() {
        if (self::$_instance == null) {
            self::$_instance = new Library_Payment_Client();
        }
        return self::$_instance;
    }

    /**
     * 
     * @param type $order
     * @param type $in_process
     * @param type $send_to_server
     * @return Library_Payment_Data_Order
     */
    public function save_current_order($order, $in_process, $send_to_server = false) {
        $session_key = 'order_' . $in_process;
        $order = serialize($order);
        Session::instance()->set($session_key, $order);
        if ($send_to_server) {
            $result = $this->call_api('saveorder', array('order' => $order));
            //print_r($result);die;
            $order = new Library_Payment_Data_Order();
            if (isset($result['status']) && $result['status'] == PaymentConstant::RESPONSE_STATUS_OK) {
                $order->from_data_array($result['data']['order']);
                $this->remove_current_order($in_process);
                if ($order->getPayment_method() == PaymentConstant::METHOD_PAYOO) {
                    $path = $this->get_api_url('payment/payoo/checkout') . '?order_id=' . $order->getId();
                    Controller::redirect($path);
                    die;
                }
                if ($order->getPayment_method() == PaymentConstant::METHOD_SENPAY) {
                    $path = $this->get_api_url('payment/senpay/checkout') . '?order_id=' . $order->getId();
                    Controller::redirect($path);
                    die;
                }
            }
        }
        return $order;
    }

    public function get_current_order($in_process) {

        if (empty($this->_user_id)) {
            $user_id = 0;
        } else {
            $user_id = $this->_user_id;
        }
        $session_user_key = 'user_' . $in_process;
        $old_user_id = Session::instance()->get($session_user_key, 0);
        Session::instance()->set($session_user_key, $user_id);

        $session_order_key = 'order_' . $in_process;
        $order = null;
        if ($user_id == $old_user_id) {
            $order = Session::instance()->get($session_order_key);
        } else {
            if ($user_id != 0) { //logout, end session
                $order = Session::instance()->get($session_order_key);
            }
        }
        if (!empty($order)) {
            $order = unserialize($order);
        } else {
            $order = $this->create_new_order();
            $this->save_current_order($order, $in_process, false);
        }
        // do not set customer_id for order here
        // it should be set when using
        // $order->setCustomer_id($this->_user_id);  
        return $order;
    }

    public function create_new_order() {
        $order = new Library_Payment_Data_Order();
        //$order->setCustomer_id($this->_user_id);
        $order->setStatus(PaymentConstant::STATUS_PENDING);
        $order->setPayment_method(PaymentConstant::METHOD_CASH);
        $order->setPaid(0);
        $order->setDescription('Đặt hàng qua mạng');
        return $order;
    }

    public function remove_current_order($in_process) {
        $session_order_key = 'order_' . $in_process;
        Session::instance()->delete($session_order_key);
    }

    public function save_current_user($user_id) {
        $this->_user_id = $user_id;
    }

    private $_call_api_subscription_list = false;
    private $_result_api_subscription_list = null;

    public function get_subscription_list($id = null) {
        $paras = array();
        if(!empty($id)){
            $paras['customer_id'] = $id;
        }
        if (!$this->_call_api_subscription_list) {
            $re = Library_Payment_Client::instance()->api('service/subscription/list',$paras);
            if (isset($re['status']) && $re['status'] == PaymentConstant::RESPONSE_STATUS_OK) {
                $arr = $re['data']['list'];
                $array = array();
                if (!empty($arr)) {
                    foreach ($arr as $v) {
                        $array[$v['id']] = $v;
                    }
                }
                $this->_result_api_subscription_list = $array;
            } else {
                Log::instance()->add(Log::ERROR, var_export($re, true))->write();
            }
            $this->_call_api_subscription_list = true;
        }
        return $this->_result_api_subscription_list;
    }
}

?>
